/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.scene.bean.ProjectAssessmentFormVO;
import com.koron.scene.domain.*;
import com.koron.scene.mapper.*;
import com.koron.scene.service.api.ProjectAssessmentService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({"classpath:deviceCheckFlow.properties"})
public class ProjectAssessmentServiceImpl implements ProjectAssessmentService, InitializingBean, AfterApprovalService {

    private static final Logger logger = LoggerFactory.getLogger(ProjectAssessmentServiceImpl.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private Util util;

    @Value("${project_assessment_template_key}")
    private String projectAssessmentTemplateKey;

    @Value("${flow.scene.setCode}")
    private String setCode;

    @Override
    public MessageBean<?> getAssessmentList(StaffBean user, String projectId, String enterpriseId, Integer page, Integer pageSize, Integer assessmentType, String corpCode) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            if (StringUtils.isBlank(projectId) || assessmentType == null) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            if (assessmentType == 0 && StringUtils.isBlank(enterpriseId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            if (assessmentType == 2 && StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            List<ProjectAssessment> list = assessmentMapper.getAssessmentList(projectId, enterpriseId, assessmentType, corpCode, start, pageSize);
            int total = assessmentMapper.getAssessmentListTotal(projectId, enterpriseId, assessmentType, corpCode);
            DataBean dataBean = new DataBean();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    void setAssessmentScore(List<ProjectAssessmentScore> list, ProjectAssessmentScoreDetailMapper scoreDetailMapper,
                            ProjectAssessment assessment) {
        Map<Integer, Double> typeFormMap = getFormTypeListByAssessmentScore(assessment);
        if (typeFormMap != null && !typeFormMap.isEmpty()) {
            List<Integer> assessmentFormTypeList = new ArrayList<>(typeFormMap.keySet());
            for (ProjectAssessmentScore score : list) {
                score.setProjectDeptScoreShow(false);
                score.setConstructorScoreShow(false);
                score.setSupervisorScoreShow(false);
                score.setSceneScoreShow(false);
                score.setScatteredProjectScoreShow(false);
                score.setProjectName(assessment.getProjectName());
                score.setEnterpriseName(assessment.getEnterpriseName());
                score.setAssessmentFormTypeList(assessmentFormTypeList);
                for (Integer type : typeFormMap.keySet()) {
                    ProjectAssessmentScoreDetail scoreDetail = scoreDetailMapper.selectFormTotalScore(score.getId(), type);
                    if (type == 0) {
                        if (scoreDetail != null) {
                            score.setProjectDeptScore(scoreDetail.getItemScore());
                        }
                        score.setProjectDeptScoreShow(true);
                    } else if (type == 1) {
                        if (scoreDetail != null) {
                            score.setConstructorScore(scoreDetail.getItemScore());
                        }
                        score.setConstructorScoreShow(true);
                    } else if (type == 2) {
                        if (scoreDetail != null) {
                            score.setSupervisorScore(scoreDetail.getItemScore());
                        }
                        score.setConstructorScoreShow(true);
                    } else if (type == 3) {
                        if (scoreDetail != null) {
                            score.setSceneScore(scoreDetail.getItemScore());
                        }
                        score.setSceneScoreShow(true);
                    } else if (type == 4) {
                        if (scoreDetail != null) {
                            score.setScatteredProjectScore(scoreDetail.getItemScore());
                        }
                        score.setScatteredProjectScoreShow(true);
                    }
                }
            }
        }

    }

    @Override
    public MessageBean<?> getAssessmentScoreList(StaffBean user, String assessmentId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessmentScoreDetailMapper scoreDetailMapper = factory.getMapper(ProjectAssessmentScoreDetailMapper.class);
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            ProjectAssessment assessment = assessmentMapper.selectById(assessmentId);
            if (assessment == null) {
                msg.setCode(BusinessCode.ASSESSMENT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_NOT_EXIST.getDescription());
                return msg;
            }
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ProjectAssessmentScore> list = scoreMapper.getListByAssessmentId(assessmentId, start, pageSize);
            if (list != null && !list.isEmpty()) {
                setAssessmentScore(list, scoreDetailMapper, assessment);
            }
            int total = scoreMapper.getListTotalByAssessmentId(assessmentId);
            DataBean dataBean = new DataBean();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> getFormData(StaffBean user, String assessmentScoreId, Integer assessmentFormType) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectAssessmentScoreMapper mapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessmentScore assessmentScore = mapper.selectByPrimaryKey(assessmentScoreId);
            ProjectAssessmentScoreDetailMapper scoreDetailMapper = factory.getMapper(ProjectAssessmentScoreDetailMapper.class);
            if (assessmentScore == null) {
                msg.setCode(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getDescription());
                return msg;
            }
            if (assessmentFormType == null || StringUtils.isBlank(assessmentScoreId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            List<ProjectAssessmentFormVO> list = mapper.getAssessmentFormData(assessmentScoreId, assessmentFormType);
            Map resultMap = new HashMap();
            resultMap.put("data", list);
            ProjectAssessmentScoreDetail scoreDetail = scoreDetailMapper.selectFormTotalScore(assessmentScoreId, assessmentFormType);
            resultMap.put("totalScore", scoreDetail == null ? null : scoreDetail.getItemScore());
            resultMap.put("comment", scoreDetail == null ? null : scoreDetail.getRemark());
            msg.setData(resultMap);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    Map<Integer, Double> getFormTypeList(Integer assessmentFormType, String projectType, String enterpriseType) {

        Map<Integer, Double> typeScore = new HashedMap();
        if (assessmentFormType == 0) {
            //相关方考核
            if (enterpriseType.equals("0")) {
                //施工方
                typeScore.put(1, 0.4);
                typeScore.put(3, 0.6);
            } else if (enterpriseType.equals("1")) {
                typeScore.put(2, 0.4);
                typeScore.put(3, 0.6);
            } else {
                return null;
            }
        } else if (assessmentFormType == 1) {
            //项目考核
//            if (projectType.equals("0")) {
            typeScore.put(0, 0.2);
            typeScore.put(1, 0.05);
            typeScore.put(2, 0.15);
            typeScore.put(3, 0.6);
//            } else if (projectType.equals("1")) {
//                formTypeList.add(4);
//                typeScore.put(4, 100);
//            } else {
//                return null;
//            }
        }
        return typeScore;
    }

    Map<Integer, Double> getFormTypeListByAssessmentScore(ProjectAssessment assessment) {
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            EnterpriseMapper enterpriseMapper = factory.getMapper(EnterpriseMapper.class);
            Project project = projectMapper.selectByPrimaryKey(assessment.getProjectId());
            Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(assessment.getEnterpriseId());
            //获取考核类型确定该考核类型需要考核的表类型
            return getFormTypeList(assessment.getAssessmentType(), project.getProjectType(), enterprise.getEnterpriseType());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<?> saveOrUpdate(StaffBean user, List<ProjectAssessmentFormVO> formList,
                                       String assessmentScoreId, Integer assessmentFormType, String comment, Double totalScore,
                                       String scoreTypeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        List<String> scoreTypeList = null;
        if (StringUtils.isNotBlank(scoreTypeListStr)) {
            scoreTypeList = Arrays.asList(scoreTypeListStr.split(","));
        }
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isBlank(assessmentScoreId) || assessmentFormType == null) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessmentScoreDetailMapper scoreDetailMapper = factory.getMapper(ProjectAssessmentScoreDetailMapper.class);
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            ProjectAssessmentScore assessmentScore = scoreMapper.selectByPrimaryKey(assessmentScoreId);
            if (assessmentScore == null) {
                msg.setCode(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getDescription());
                return msg;
            }
            if (!assessmentScore.getStaffCode().equals(user.getCode())) {
                msg.setCode(BusinessCode.HAVE_NO_RIGHT_ASSESSMENT.getCode());
                msg.setDescription(BusinessCode.HAVE_NO_RIGHT_ASSESSMENT.getDescription());
                return msg;
            }
            ProjectAssessment assessment = assessmentMapper.selectByPrimaryKey(assessmentScore.getAssessmentId());
            if (assessment == null) {
                msg.setCode(BusinessCode.ASSESSMENT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_NOT_EXIST.getDescription());
                return msg;
            }
            //获取考核类型确定该考核类型需要考核的表类型
            Map<Integer, Double> assessmentFormTypeMap = getFormTypeListByAssessmentScore(assessment);
            if (assessmentFormTypeMap == null || assessmentFormTypeMap.isEmpty()) {
                msg.setCode(BusinessCode.ASSESSMENT_TYPE_ERROR.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_TYPE_ERROR.getDescription());
                return msg;
            }

            if (formList == null || formList.isEmpty()) {
                msg.setCode(BusinessCode.ASSESSMENT_SCORE_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_SCORE_CANNOT_EMPTY.getDescription());
                return msg;
            }
            //将list转换成树进行计算 验证
            Map<String, ProjectAssessmentItem> itemMap = new HashMap();
            for (ProjectAssessmentFormVO formVO : formList) {
                ProjectAssessmentItem item = itemMap.get(formVO.getItemId());
                if (item == null) {
                    item = new ProjectAssessmentItem();
                    item.setScore(formVO.getItemScore() == null ? null : Math.abs(formVO.getItemScore()));
                    item.setAssessmentFormType(formVO.getAssessmentFormType());
                    item.setItemName(formVO.getItemName());
                    item.setBenchmarkScore(formVO.getItemBenchmarkScore());
                    item.setScoreRemark(formVO.getItemScoreRemark());
                    item.setId(formVO.getItemId());
                    itemMap.put(item.getId(), item);
                }
                Map<String, ProjectAssessmentContent> contentMap = item.getContentMap();
                if (contentMap == null) {
                    contentMap = new HashMap<>();
                    item.setContentMap(contentMap);
                }
                ProjectAssessmentContent content = contentMap.get(formVO.getContentId());
                if (content == null) {
                    content = new ProjectAssessmentContent();
                    content.setScore(formVO.getContentScore() == null ? null : Math.abs(formVO.getContentScore()));
                    content.setContentName(formVO.getContentName());
                    content.setBenchmarkScore(formVO.getContentBenchmarkScore());
                    content.setScoreRemark(formVO.getContentScoreRemark());
                    content.setId(formVO.getContentId());
                    contentMap.put(content.getId(), content);
                }
                Map<String, ProjectAssessmentDetailItem> detailItemMap = content.getDetailItemMap();
                if (detailItemMap == null) {
                    detailItemMap = new HashMap<>();
                    content.setDetailItemMap(detailItemMap);
                }
                ProjectAssessmentDetailItem detailItem = detailItemMap.get(formVO.getDetailItemId());
                if (detailItem == null) {
                    detailItem = new ProjectAssessmentDetailItem();
                    detailItem.setItemName(formVO.getDetailItemName());
                    detailItem.setScoreRemark(formVO.getDetailItemScoreRemark());
                    detailItem.setId(formVO.getDetailItemId());
                    detailItem.setScore(formVO.getDetailItemScore() == null ? null : Math.abs(formVO.getDetailItemScore()));
                    detailItemMap.put(detailItem.getId(), detailItem);
                }
            }
            List<ProjectAssessmentScoreDetail> scoreDetailList = new ArrayList<>();
            if (scoreTypeList == null) {
                scoreTypeList = new ArrayList<>();
            }
            //检查项总得分
            Double itemTotalScore = 0.0;
            for (Map.Entry<String, ProjectAssessmentItem> itemEntry : itemMap.entrySet()) {
                ProjectAssessmentItem item = itemEntry.getValue();
                if (item != null) {
                    ProjectAssessmentScoreDetail scoreDetail = new ProjectAssessmentScoreDetail();
                    Map<String, ProjectAssessmentContent> contentMap = item.getContentMap();
                    if (contentMap != null) {
                        Double contentTotalScore = 0.0;
                        for (Map.Entry<String, ProjectAssessmentContent> contentEntry : contentMap.entrySet()) {
                            ProjectAssessmentContent content = contentEntry.getValue();
                            if (content != null) {
                                ProjectAssessmentScoreDetail scoreDetail1 = new ProjectAssessmentScoreDetail();
                                Map<String, ProjectAssessmentDetailItem> detailItemMap = content.getDetailItemMap();
                                if (detailItemMap != null) {
                                    Double detailItemTotalScore = 0.0;
                                    for (Map.Entry<String, ProjectAssessmentDetailItem> detailItemEntry : detailItemMap.entrySet()) {
                                        ProjectAssessmentDetailItem detailItem = detailItemEntry.getValue();
                                        if (detailItem != null) {
                                            ProjectAssessmentScoreDetail scoreDetail2 = new ProjectAssessmentScoreDetail();
                                            scoreDetail2.setAssessmentScoreId(assessmentScoreId);
                                            scoreDetail2.setItemId(detailItem.getId());
                                            scoreDetail2.setItemType(0);
                                            scoreDetail2.setItemScore(detailItem.getScore() == null ? 0 : detailItem.getScore());
                                            scoreDetail2.setRemark(detailItem.getScoreRemark());
                                            scoreDetail2.setAssessmentFormType(assessmentFormType);
                                            BaseEntityUtil.setAddBaseProperties(scoreDetail2, user);
                                            scoreDetailList.add(scoreDetail2);
                                            if (detailItem.getScore() != null) {
                                                detailItemTotalScore += detailItem.getScore();
                                            }
                                        }
                                    }
                                    //评分细则  与 检查内容分数校验
                                    Double contentBenchmarkScore = content.getBenchmarkScore();
                                    List<String> filterList = scoreTypeList.stream().filter(type -> type.equals("2")).collect(Collectors.toList());
                                    if (filterList == null || filterList.isEmpty()) {
                                        if (contentBenchmarkScore - detailItemTotalScore < 0) {
                                            content.setScore(0.0);
                                        } else {
                                            content.setScore(contentBenchmarkScore - detailItemTotalScore);
                                        }
                                    } else {
                                        if (content.getScore() == null) {
                                            if (contentBenchmarkScore - detailItemTotalScore < 0) {
                                                content.setScore(contentBenchmarkScore);
                                            } else {
                                                content.setScore(contentBenchmarkScore - detailItemTotalScore);
                                            }
                                        }
                                    }

                                }
                                scoreDetail1.setAssessmentScoreId(assessmentScoreId);
                                scoreDetail1.setItemId(content.getId());
                                scoreDetail1.setItemType(1);
                                scoreDetail1.setItemScore(content.getScore());
                                scoreDetail1.setRemark(content.getScoreRemark());
                                scoreDetail1.setAssessmentFormType(assessmentFormType);
                                contentTotalScore += content.getScore();
                                BaseEntityUtil.setAddBaseProperties(scoreDetail1, user);
                                scoreDetailList.add(scoreDetail1);
                            }
                        }
                        //计算检查内容总分与检查项分数
                        Double itemBenchmarkScore = item.getBenchmarkScore();
                        List<String> filterList = scoreTypeList.stream().filter(type -> type.equals("3")).collect(Collectors.toList());
                        if (filterList == null || filterList.isEmpty()) {
                            List<String> filterList1 = scoreTypeList.stream().filter(type -> type.equals("2")).collect(Collectors.toList());
                            if (filterList1 == null || filterList1.isEmpty()) {
                                if (itemBenchmarkScore - contentTotalScore < 0) {
                                    item.setScore(itemBenchmarkScore);
                                } else {
                                    item.setScore(contentTotalScore);
                                }
                            } else {
                                item.setScore(contentTotalScore);
                            }

                        } else {
                            if (item.getScore() == null) {
                                if (itemBenchmarkScore - contentTotalScore < 0) {
                                    item.setScore(itemBenchmarkScore);
                                } else {
                                    item.setScore(contentTotalScore);
                                }
                            }
                        }

                    }
                    scoreDetail.setAssessmentScoreId(assessmentScoreId);
                    scoreDetail.setItemId(item.getId());
                    scoreDetail.setItemType(2);
                    scoreDetail.setItemScore(item.getScore());
                    scoreDetail.setRemark(item.getScoreRemark());
                    scoreDetail.setAssessmentFormType(assessmentFormType);
                    itemTotalScore += item.getScore();
                    BaseEntityUtil.setAddBaseProperties(scoreDetail, user);
                    scoreDetailList.add(scoreDetail);
                }
            }
            //校验总分数是否正确
            List<String> filterList = scoreTypeList.stream().filter(type -> type.equals("4")).collect(Collectors.toList());
            if (filterList == null || filterList.isEmpty()) {
                totalScore = itemTotalScore;
            } else {
                if (totalScore == null) {
                    totalScore = itemTotalScore;
                }
            }
            //保存得分
            ProjectAssessmentScoreDetail totalScoreDetail = new ProjectAssessmentScoreDetail();
            totalScoreDetail.setAssessmentScoreId(assessmentScoreId);
            totalScoreDetail.setItemId(null);
            totalScoreDetail.setItemType(3);
            totalScoreDetail.setItemScore(totalScore);
            totalScoreDetail.setRemark(comment);
            totalScoreDetail.setAssessmentFormType(assessmentFormType);
            BaseEntityUtil.setAddBaseProperties(totalScoreDetail, user);
            scoreDetailList.add(totalScoreDetail);
            //删除该次得分记录的该考核表类型之前的打分明细
            scoreDetailMapper.deleteByScoreIdAndFormType(assessmentScoreId, assessmentFormType);
            //保存所有得分
            scoreDetailMapper.insertList(scoreDetailList);
            //检查是否审核完成
            boolean result = true;
            Double scoreTotal = 0.0;
            for (Map.Entry<Integer, Double> entry : assessmentFormTypeMap.entrySet()) {
                Integer type = entry.getKey();
                Double percentage = entry.getValue();
                ProjectAssessmentScoreDetail scoreDetail = scoreDetailMapper.selectFormTotalScore(assessmentScoreId, type);
                if (scoreDetail == null) {
                    result = false;
                    break;
                }
                Double formScore = scoreDetail.getItemScore() == null ? 0 : scoreDetail.getItemScore();
                Double score = new BigDecimal(formScore * percentage).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                scoreTotal += score;
            }
            if (result) {
                ProjectAssessmentScore assessmentScoreUp = new ProjectAssessmentScore();
//            assessmentScoreUp.setComment(null);
                assessmentScoreUp.setId(assessmentScoreId);
                //保存总分并更新状态
                assessmentScoreUp.setState(1);
                assessmentScoreUp.setResultScore(scoreTotal);
                scoreMapper.updateByPrimaryKeySelective(assessmentScoreUp);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    MessageBean<ProjectAssessment> checkAndBuildAssessment(StaffBean user, String projectId, String enterpriseId, Integer assessmentType, String corpCode) {
        MessageBean<ProjectAssessment> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), ProjectAssessment.class);
        ProjectAssessment projectAssessment = new ProjectAssessment();
        if (user == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (assessmentType == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(projectId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (assessmentType == 0 && StringUtils.isBlank(enterpriseId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (assessmentType == 2 && StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        projectAssessment.setAssessmentType(assessmentType);
        projectAssessment.setProjectId(projectId);
        projectAssessment.setEnterpriseId(enterpriseId);
        projectAssessment.setCorpCode(corpCode);
        projectAssessment.setPromoterCode(user.getCode());
        projectAssessment.setPromoterName(user.getName());
        projectAssessment.setStartDate(new Date());
        projectAssessment.setState(0);
        msg.setData(projectAssessment);
        return msg;
    }

    @Override
    public MessageBean<?> initiateAssessment(StaffBean user, String projectId, String enterpriseId, Integer assessmentType, List<StaffBean> staffList, String corpCode) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessmentMapper mapper = factory.getMapper(ProjectAssessmentMapper.class);
            MessageBean<ProjectAssessment> messageBean = checkAndBuildAssessment(user, projectId, enterpriseId, assessmentType, corpCode);
            if (messageBean.getCode() != 0) {
                return messageBean;
            }
            ProjectAssessment projectAssessment = messageBean.getData();
            BaseEntityUtil.setAddBaseProperties(projectAssessment, user);
            if (staffList == null || staffList.isEmpty()) {
                msg.setCode(BusinessCode.ASSESSMENT_STAFF_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_STAFF_CANNOT_EMPTY.getDescription());
                return msg;
            }
            //打分统计表
            List<ProjectAssessmentScore> scoreList = new ArrayList<>();
            List<String> idList = new ArrayList<>();
            for (StaffBean staff : staffList) {
                if (!idList.contains(staff.getCode())) {
                    idList.add(staff.getCode());
                    ProjectAssessmentScore score = new ProjectAssessmentScore();
                    score.setAssessmentId(projectAssessment.getId());
                    score.setStaffCode(staff.getCode());
                    score.setStaffName(staff.getName());
                    score.setDeptCode(staff.getDepartmentCode());
                    score.setDeptName(staff.getDepartmentname());
                    DepartmentTreeBean crop = (DepartmentTreeBean) util.corp(user.getCode()).getData();
                    score.setCorpCode(crop.getDepartmentCode());
                    score.setCorpName(crop.getName());
                    score.setState(0);
                    BaseEntityUtil.setAddBaseProperties(score, user);
                    scoreList.add(score);
                }
            }
            //保存
            mapper.insert(projectAssessment);
            if (!scoreList.isEmpty()) {
                scoreMapper.insertList(scoreList);
            }
            List<String> staffCodeList = staffList.stream().map(staffBean -> staffBean.getUserid()).collect(Collectors.toList());
            //开启流程
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(ProjectAssessmentService.class.getName());
            if (assessmentType == 0) {
                audit.setFlowName("相关方考核");
                audit.setTitle("相关方考核");
            } else if (assessmentType == 1) {
                audit.setFlowName("项目考核");
                audit.setTitle("项目考核");
            } else if (assessmentType == 2) {
                audit.setFlowName("项目部考核");
                audit.setTitle("项目部考核");
            }
            DepartmentTreeBean corp = (DepartmentTreeBean) util.corp(user.getCode()).getData();
            audit.setCorpCode(corp.getDepartmentCode());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("考核提交");
            audit.setState(1);
            audit.setSetCode(setCode);
            audit.setTemplateKey(projectAssessmentTemplateKey);
            audit.setSetCode(setCode);
            audit.setInitiatorAccount(user.getUserid());
            audit.setBusinessIds(projectAssessment.getId());
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : staffCodeList) {
                codes.append(code).append(",");
            }
            businessMap.put("examiners", codes.toString().substring(0,codes.length()-1));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("发起考核失败");
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("发起考核成功");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> getProcessData(StaffBean user, String assessmentId) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessmentScoreDetailMapper scoreDetailMapper = factory.getMapper(ProjectAssessmentScoreDetailMapper.class);
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            ProjectAssessment assessment = assessmentMapper.selectById(assessmentId);
            if (assessment == null) {
                msg.setCode(BusinessCode.ASSESSMENT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_NOT_EXIST.getDescription());
                return msg;
            }
            List<ProjectAssessmentScore> list = scoreMapper.getListByAssessmentIdAndStaffCode(assessmentId, user.getCode());
            if (list != null && !list.isEmpty()) {
                setAssessmentScore(list, scoreDetailMapper, assessment);
            }
            msg.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> checkAssessmentScoreState(StaffBean user, String assessmentId) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            List<ProjectAssessmentScore> list = scoreMapper.getListByAssessmentIdAndStaffCode(assessmentId, user.getCode());
//            ProjectAssessmentScore score = scoreMapper.selectByPrimaryKey(assessmentScoreId);
            Integer state = null;
            if (list != null && !list.isEmpty()) {
                if (list.stream().anyMatch(score -> score.getState() == 0)) {
                    state = 0;
                } else {
                    state = 1;
                }
            } else {
                msg.setCode(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_SCORE_NOT_EXIST.getDescription());
                return msg;
            }
            msg.setData(state);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            String id = audit.getBusinessIds();
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            ProjectAssessmentScoreMapper scoreMapper = factory.getMapper(ProjectAssessmentScoreMapper.class);
            ProjectAssessment projectAssessment = assessmentMapper.selectByPrimaryKey(id);
            if (projectAssessment != null) {

                //查询所有打分记录
                List<ProjectAssessmentScore> scoreList = scoreMapper.getListByAssessmentId(id, null, null);
                if (scoreList != null && !scoreList.isEmpty()) {
                    //计算所有平均分
                    Double totalScore = 0.0;
                    boolean result = true;
                    for (ProjectAssessmentScore assessmentScore : scoreList) {
                        if (assessmentScore.getState().equals(0)) {
                            result = false;
                            break;
                        }
                        totalScore += assessmentScore.getResultScore();
                    }
                    if (result) {
                        Double averageScore = totalScore / scoreList.size();
                        projectAssessment.setResultScore(averageScore);
                        projectAssessment.setState(1);
                        projectAssessment.setEndDate(new Date());
                        assessmentMapper.updateByPrimaryKeySelective(projectAssessment);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(ProjectAssessmentService.class.getName(), this);
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
